/**
 * @author laiwp
 * @classedescription  系统初始化
 * @version 0.1.0
 * port:8083/sport/list
 */
var express = require('express');
var path = require('path');  //用于处理目录的对象，提高开发效率。
var favicon = require('static-favicon');

var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var settings = require('./settings');
var flash = require('connect-flash');
//var mongoose = require('mongoose');

var mysqlConfig = require('./mysql.js');  //
var mysql = require('mysql');  //调用MySQL模块


var logger = require('./logger').logger;
var connect = require('connect');
//var controller  = require("./routers/menu/util/controller");
var ejs = require('ejs');

var app_version = "0.0.1";
var app = exports.app = express();

var OAuth = require('wechat-oauth');
var oauth_client = new OAuth(settings.appid, settings.secret);
global.oauth_client = oauth_client;
var dbDao=require('./models/dbBase.js');

var log = require('./logger.js');
//设置session

var session    = require('express-session');


app.use(session({
    resave: true,
    saveUninitialized: true,
    rolling: true,
    secret: 'sportsite',
    proxy: false,
    cookie: { maxAge:30 * 24 * 60 * 60 * 1000, httpOnly:true, secure:false }
}));
app.set('views', __dirname + '/views');  //放模板文件的目录
app.engine('.html', ejs.__express);  //注册模板引擎  让ejs能够识别后缀为’.html’的文件
//app.set('view engine', 'html');  //设置调用render函数时能自动为我们加上’.html’ 后缀
app.use(favicon(__dirname+ '/public/images/icon.ico'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(flash());
app.use(express.static(path.join(__dirname, 'public')));  //托管静态文件
// 全局头设置,允许跨域请求
app.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By",' 3.2.1');
    next();
});
var initTable = require('./models/tableInit.js');
initTable();

//加载路由控制器;
var qcgMenu = require('./routers/qcgMenu.js');
var wechat = require('./routers/wechat.js');
var gymResource = require('./routers/gymResource.js');
var gymDetails = require('./routers/gymDetails.js');
var userPhone = require('./routers/userPhone.js');

//路由
app.use(qcgMenu);
app.use(wechat);
//app.use(gymResource);
//app.use(gymDetails);
app.use(userPhone);

var gymManager= require('./routers/v1/gymManager.js');
var member= require('./routers/v1/member.js');
var order= require('./routers/v1/order.js');
var pay= require('./routers/v1/pay.js');
var wechatMenu= require('./routers/menu/wechatMenu.js');
var sms= require('./routers/v1/sms/sms.js');

app.use('/api/v1/gymManager',gymManager);
app.use('/api/v1/member',member);
app.use('/api/v1/order',order);
app.use('/api/v1/pay',pay);
app.use('/wechatMenu',wechatMenu);

app.use('/api/v1/sms',sms);
//controller.bootControllers(app);
/**
 * 连接mysql
 * 创建一个connection
 */
var connection = mysql.createConnection(mysqlConfig.mysql);
connection.connect(function(err){
    if(err){
        console.log('[mysql数据库链接失败!!!] - :'+err);
        return;
    }
    console.log('[mysql数据库链接成功]  succeed!');
    app.listen(settings.hostport, settings.hostname);
    logger.info('Server started on port ' + settings.hostname + ':' + settings.hostport + ' (' + process.env.NODE_ENV + ')');
});

//接收微信公众平台发过来的XML数据
app.use(function(req, res, next) {
    var data = '';
    console.log(req.url);

    if(req.url.substring(0,5) == "/m/wx" || req.url.substring(0,9) == "/wxpay/ok"||req.url.substring(0,15) == "/appalipay/back"){
        if(req.param("echostr")){
            next();
        }else{
            req.setEncoding('utf8');
            req.on('data', function(chunk) {
                data += chunk;
            });
            console.log("======== appserver /m/wx=========");
            req.on('end', function() {
                req.body = data;
                next();
            });
        }
    }else if(req.url.substring(0,5) == "/m/qy"){
        req.setEncoding('utf8');
        req.on('data', function(chunk) {
            data += chunk;
        });
        console.log("======== appserver /m/qy=========");
        console.log(data);
        req.on('end', function() {
            req.body = data;
            next();
        });
    }else{
        next();
    }

});





